package com.banshuibao.bsb_android.activity;

import android.Manifest;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.banshuibao.bsb_android.Constants;
import com.banshuibao.bsb_android.R;
import com.banshuibao.bsb_android.http.HttpResponse;
import com.banshuibao.bsb_android.http.HttpUtil;
import com.banshuibao.bsb_android.model.ApplyToExpertModel;
import com.banshuibao.bsb_android.model.LookModel;
import com.banshuibao.bsb_android.util.CameraUtil;
import com.banshuibao.bsb_android.util.IntentManager;
import com.banshuibao.bsb_android.util.QuickDoubleClickable;
import com.banshuibao.bsb_android.util.XToast;
import com.zx.uploadlibrary.listener.impl.UIProgressListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.List;

public class ApplyToExpertActivity extends PermissionBaseActivity implements View.OnClickListener, CameraUtil.OnClickOkListener {

    private TextView file_name, menu;

    private ImageView delete;

    private RelativeLayout select_file, show_filename, zhenjian;

    private File file;

    private Dialog dialog;

    private ProgressBar progressBar;

    private TextView download_status;

    private String fileName;

    private EditText name, year, scyw, person, money;

    private CheckBox checkBox1, checkBox2, checkBox3;

    private RecyclerView recycler;

    private CameraUtil cameraUtil;

    private String[] images = new String[0];

    private String i = "";
    private String duty = "";
    private int flag;
    private String uuid;
    private String formerFile;
    private String realFile;

    private int delete_flag = 100;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_apply_to_expert);
        initView();
        getData();
    }

    //读取用户信息得到申请状态
    private void getUserPost() {
        HttpUtil.doPost(Constants.Url.LOOK_APPLY, null, new HttpResponse(this, LookModel.class) {
            @Override
            public void onResult(Object obj) {
                LookModel lookModel = (LookModel) obj;
                LookModel.Data data = lookModel.getData();
                uuid = data.getUuid();
                String reason = data.getReason();
                setData(reason);
                name.setText(data.getName());
                year.setText(String.valueOf(data.getYear()));
                money.setText(String.valueOf(data.getAdvicePrice()));
                scyw.setText(data.getSkill());
                person.setText(data.getProfile());
                select_file.setVisibility(View.GONE);
                show_filename.setVisibility(View.VISIBLE);
                formerFile = data.getFormerFile();
                file_name.setText(formerFile);
                realFile = data.getRealFile();
            }
        });
    }

    private void setData(String reason) {
        XToast.showToast(ApplyToExpertActivity.this, reason);
    }

    private void setPost() {

        if (TextUtils.isEmpty(name.getText().toString().trim())) {
            toToast("请输入您的姓名");
            cancelProgressDialog();
            return;
        }

        if (!checkBox1.isChecked() && !checkBox2.isChecked() && !checkBox3.isChecked()) {
            toToast("请选择一项职务");
            cancelProgressDialog();
            return;
        }

        if (TextUtils.isEmpty(year.getText().toString().trim())) {
            toToast("请输入您的从业年限");
            cancelProgressDialog();
            return;
        }

        String s = money.getText().toString().trim();
        if (!TextUtils.isEmpty(s)) {
            double i = Double.parseDouble(s);
            if ( i < 0) {
                toToast("请输入您的咨询价格,价格大于0");
                cancelProgressDialog();
                return;
            }
        }else {
            toToast("请输入您的咨询价格,价格大于0");
            cancelProgressDialog();
            return;
        }

        if (TextUtils.isEmpty(scyw.getText().toString().trim())) {
            toToast("请输入您的擅长业务");
            cancelProgressDialog();
            return;
        }

        if (TextUtils.isEmpty(person.getText().toString().trim())) {
            toToast("请输入您的个人简介");
            cancelProgressDialog();
            return;
        }

        if (TextUtils.isEmpty(fileName) || file == null) {
            toToast("请先上传您的简历");
            cancelProgressDialog();
            return;
        }

        if (images.length == 0) {
            toToast("请先上传您的资格证书");
            cancelProgressDialog();
            return;
        }
        ApplyToExpertModel model = new ApplyToExpertModel();
        model.setUuid(uuid);
        model.setName(name.getText().toString().trim());
        if (checkBox1.isChecked()) {
            this.i = "2";
            if (TextUtils.isEmpty(duty)) {
                duty = this.i;
            } else {
                duty = duty + "," + this.i;
            }
        }
        if (checkBox2.isChecked()) {
            this.i = "3";
            if (TextUtils.isEmpty(duty)) {
                duty = this.i;
            } else {
                duty = duty + "," + this.i;
            }
        }
        if (checkBox3.isChecked()) {
            this.i = "1";
            if (TextUtils.isEmpty(duty)) {
                duty = this.i;
            } else {
                duty = duty + "," + this.i;
            }
        }
        model.setDuty(duty);
        model.setYear(Integer.parseInt(year.getText().toString().trim()));
        model.setSkill(scyw.getText().toString().trim());
        model.setProfile(person.getText().toString().trim());
        if (file != null) {
            model.setFormerFile(file.getName());
        } else {
            model.setFormerFile(formerFile);
        }
        if (!TextUtils.isEmpty(fileName)) {
            model.setRealFile(fileName);
        } else {
            model.setRealFile(realFile);
        }
        model.setAdvicePrice(Double.parseDouble(money.getText().toString().trim()));
        model.setCredImg(images);
        model.setType("edit");
        HttpUtil.doPost(Constants.Url.APPLYEXPERT, model, new HttpResponse(this) {
            @Override
            public void onResult(Object obj) {
                XToast.showToast(ApplyToExpertActivity.this, "您已成功提交,请耐心等待");
                IntentManager.goApplyToExpertTwoActivity(ApplyToExpertActivity.this);
                finish();
            }

            @Override
            public void responseEnd() {
                super.responseEnd();
                cancelProgressDialog();
            }
        });
    }

    private void getData() {
        //1 首次申请  2 编辑
        flag = getIntent().getIntExtra("flag", 0);
        if (flag == 2) {
            getUserPost();
        }
    }

    private void initView() {
        setTitleText("申请做答疑专家");
        menu = findViewById(R.id.menu);
        menu.setVisibility(View.VISIBLE);
        menu.setText("提交");
        menu.setOnClickListener(this);
        select_file = findViewById(R.id.jianli);
        show_filename = findViewById(R.id.show_filename);
        file_name = findViewById(R.id.filename);
        delete = findViewById(R.id.delete);
        delete.setOnClickListener(this);
        select_file.setOnClickListener(this);

        name = findViewById(R.id.edit_name);
        year = findViewById(R.id.edit_year);
        scyw = findViewById(R.id.edit_s);
        person = findViewById(R.id.edit_person);
        money = findViewById(R.id.edit_money);

        checkBox1 = findViewById(R.id.check1);
        checkBox2 = findViewById(R.id.check2);
        checkBox3 = findViewById(R.id.check3);

        recycler = findViewById(R.id.recycler);
        zhenjian = findViewById(R.id.zhengjian);
        zhenjian.setOnClickListener(this);
        cameraUtil = new CameraUtil(this, 3);
        cameraUtil.setOnClickOkListener(this);
        cameraUtil.setLayout(recycler);

        scyw.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (editable.length() >= 300)
                    toToast("您已输入300字,无法继续输入");
            }
        });
    }

    @Override
    public void successGrantPermission(int requestCode) {
        IntentManager.goFilePickerActivity(this, new String[]{"doc", "docx", "dot", "dotx"});
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK)
            switch (requestCode) {
                case FilePickerActivity.FILE_RESULT_CODE:
                    try {
                        String path = data.getStringExtra(FilePickerActivity.FILE_RESULT);
                        this.file = new File(path);
                        int length = this.file.getName().length();
                        if (length <= 20) {
                            select_file.setVisibility(View.GONE);
                            show_filename.setVisibility(View.VISIBLE);
                            file_name.setText(this.file.getName());
                        } else {
                            toToast("请选择20字以内文件名的文件,重新上传");
                            file = null;
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        XToast.showToast(this, "文件异常");
                    }
                    break;
            }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.menu:
                if (QuickDoubleClickable.isDoubleClick())
                    return;
                if (flag == 2 && delete_flag == 100) {
                    showProgressDialog();
                    setPost();
                }else {
                    showUploadDialog();
                }
                break;
            case R.id.jianli:
                requestUserPermission(view, Manifest.permission.WRITE_EXTERNAL_STORAGE, 1);
                break;
            case R.id.zhengjian:
                cameraUtil.goPhoto(true);
                break;
            case R.id.delete:
                if (flag == 2) {
                    delete_flag = 200;
                    if (file == null) {
                        select_file.setVisibility(View.VISIBLE);
                        show_filename.setVisibility(View.GONE);
                    }else {
                        file = null;
                        select_file.setVisibility(View.VISIBLE);
                        show_filename.setVisibility(View.GONE);
                    }
                } else {
                    if (file != null) {
                        file = null;
                        select_file.setVisibility(View.VISIBLE);
                        show_filename.setVisibility(View.GONE);
                    }
                }
                break;
        }
    }

    private void showUploadDialog() {
        if (TextUtils.isEmpty(name.getText().toString().trim())) {
            toToast("请输入您的姓名");
            return;
        }

        if (!checkBox1.isChecked() && !checkBox2.isChecked() && !checkBox3.isChecked()) {
            toToast("请选择一项职务");
            return;
        }

        if (TextUtils.isEmpty(year.getText().toString().trim())) {
            toToast("请输入您的从业年限");
            return;
        }

        if (TextUtils.isEmpty(money.getText().toString().trim())) {
            toToast("请输入您的咨询价格");
            return;
        }

        if (TextUtils.isEmpty(scyw.getText().toString().trim())) {
            toToast("请输入您的擅长业务");
            return;
        }

        if (TextUtils.isEmpty(person.getText().toString().trim())) {
            toToast("请输入您的个人简介");
            return;
        }

        if (file == null) {
            XToast.showToast(this, "请选择您要上传的简历");
            return;
        }

        if (images.length == 0) {
            toToast("请先上传您的资格证书");
            return;
        }

        if (dialog == null) {
            View view = LayoutInflater.from(this).inflate(R.layout.dialog_download_progress, null);
            TextView title = (TextView) view.findViewById(R.id.title);
            title.setText("上传中请稍后");
            download_status = (TextView) view.findViewById(R.id.download_status);
            download_status.setText("正在上传");
            progressBar = (ProgressBar) view.findViewById(R.id.progress_bar);
            dialog = new AlertDialog.Builder(this).setView(view).setCancelable(false).create();
        }
        if (!this.isDestroyed())
            dialog.show();
        uploadFile();
    }

    private void setUpload_status(String msg) {
        if (download_status != null) {
            download_status.setText(msg);
        }
    }

    private void uploadFile() {
        UIProgressListener listener = new UIProgressListener() {
            @Override
            public void onUIProgress(long l, long l1, boolean b) {
                if (l1 == 0)
                    return;
                int progress = (int) ((100 * l) / l1);
                progressBar.setProgress(progress);
                if (dialog != null && dialog.isShowing())
                    setUpload_status("上传进度: " + progress + "%");
            }

            @Override
            public void onUIStart(long currentBytes, long contentLength, boolean done) {
                super.onUIStart(currentBytes, contentLength, done);
            }

            @Override
            public void onUIFinish(long currentBytes, long contentLength, boolean done) {
                super.onUIFinish(currentBytes, contentLength, done);

            }
        };
        HttpUtil.doUpload(Constants.Url.BUSER_UPLOAD, file.getAbsolutePath(), listener, new HttpResponse(this) {

            @Override
            public void onResult(Object obj) {
                try {
                    JSONObject jsonObject = new JSONObject((String) obj);
                    fileName = jsonObject.optString("data");
//                    toastUpload_status("上传成功");

                    if (flag == 2) {
                        showProgressDialog();
                        setPost();
                    } else {
                        showProgressDialog();
                        commit();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    toastUpload_status("上传失败");
                }
            }

            @Override
            public void onError(String code, String msg) {
                super.onError(code, msg);
                toastUpload_status("上传失败"+msg);
            }

            @Override
            public void onFailure(String msg) {
                super.onFailure(msg);
                toastUpload_status("上传失败");
            }

            @Override
            public void responseEnd() {
                super.responseEnd();
                if (dialog != null && dialog.isShowing()) {
                    dialog.dismiss();
                }
            }
        });
    }

    private void toastUpload_status(String msg) {
        setUpload_status(msg);
        toToast(msg);
    }

    private void toToast(String msg) {
        XToast.showToast(this, msg);
    }

    private void commit() {
        if (TextUtils.isEmpty(name.getText().toString().trim())) {
            toToast("请输入您的姓名");
            cancelProgressDialog();
            return;
        }

        if (!checkBox1.isChecked() && !checkBox2.isChecked() && !checkBox3.isChecked()) {
            toToast("请选择一项职务");
            cancelProgressDialog();
            return;
        }

        if (TextUtils.isEmpty(year.getText().toString().trim())) {
            toToast("请输入您的从业年限");
            cancelProgressDialog();
            return;
        }

        String s = money.getText().toString().trim();
        int i = Integer.parseInt(s);
        if (TextUtils.isEmpty(s) && i >= 0) {
            toToast("请输入您的咨询价格,价格大于0");
            cancelProgressDialog();
            return;
        }

        if (TextUtils.isEmpty(scyw.getText().toString().trim())) {
            toToast("请输入您的擅长业务");
            cancelProgressDialog();
            return;
        }

        if (TextUtils.isEmpty(person.getText().toString().trim())) {
            toToast("请输入您的个人简介");
            cancelProgressDialog();
            return;
        }

        if (TextUtils.isEmpty(fileName) || file == null) {
            toToast("请先上传您的简历");
            cancelProgressDialog();
            return;
        }

        if (images.length == 0) {
            toToast("请先上传您的资格证书");
            cancelProgressDialog();
            return;
        }

        ApplyToExpertModel model = new ApplyToExpertModel();
        model.setName(name.getText().toString().trim());
        if (checkBox1.isChecked()) {
            this.i = "2";
            if (TextUtils.isEmpty(duty)) {
                duty = this.i;
            } else {
                duty = duty + "," + this.i;
            }
        }
        if (checkBox2.isChecked()) {
            this.i = "3";
            if (TextUtils.isEmpty(duty)) {
                duty = this.i;
            } else {
                duty = duty + "," + this.i;
            }
        }
        if (checkBox3.isChecked()) {
            this.i = "1";
            if (TextUtils.isEmpty(duty)) {
                duty = this.i;
            } else {
                duty = duty + "," + this.i;
            }
        }
        model.setDuty(duty);
        model.setYear(Integer.parseInt(year.getText().toString().trim()));

        model.setSkill(scyw.getText().toString().trim());
        model.setProfile(person.getText().toString().trim());
        model.setFormerFile(file.getName());
        model.setRealFile(fileName);
        model.setAdvicePrice(Double.parseDouble(s));
        model.setCredImg(images);
        model.setType("add");
        HttpUtil.doPost(Constants.Url.APPLYEXPERT, model, new HttpResponse(this) {
            @Override
            public void onResult(Object obj) {
                XToast.showToast(ApplyToExpertActivity.this, "您已成功提交,请耐心等待");
                IntentManager.goApplyToExpertTwoActivity(ApplyToExpertActivity.this);
                finish();
            }

            @Override
            public void responseEnd() {
                super.responseEnd();
                cancelProgressDialog();
            }
        });
    }


    @Override
    public void gobackData(List<String> list) {
        if (list != null) {
            images = list.toArray(new String[list.size()]);
        }
    }

    //点击隐藏输入框之外 隐藏输入框
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev)) {

                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
            return super.dispatchTouchEvent(ev);
        }
        // 必不可少，否则所有的组件都不会有TouchEvent了
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }

    public boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] leftTop = {0, 0};
            //获取输入框当前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 点击的是输入框区域，保留点击EditText的事件
                return false;
            } else {
                return true;
            }
        }
        return false;
    }
}
